
function toQuery(obj:any){
  let str = '';
  for(let k in obj){
    str += `${k}=${obj[k]}&`
  }
  str = str.slice(0,str.length-1)
  return str
}
export interface IHttpOption{
  method?:'get'|'post';
  data?:{};
  headers?:{}
}
export const http = (url:string,option:IHttpOption)=>{
  const {
    method='get',
    data={},
    headers = {}
  } = option || {};
  let params = {
    method,
    body:method === 'get' ? undefined : JSON.stringify(data),
    headers:{
      'content-type':"application/json",
      ...headers
    }
  }
  if(method === 'get'){
    url += '?'+toQuery(data)
  }

  return fetch(url,params).then(res=>res.json())
}

export const $get = function(url:string,data?:any){
  return http(url,{method:'get',data})
}
export const $post = function(url:string,data?:any){
  return http(url,{method:'post',data})
}